#ifndef VIDEOSURFACE_H
#define VIDEOSURFACE_H

#include <QtQuick/QQuickPaintedItem>
#include <QRect>
#include <QSize>
#include <QTimer>

#include <vector>
#include <map>
#include "../deskcore/video/video.h"
#include <vpx/vpx_image.h>
#include "../deskcore/keyevent/KeyMap.h"

class VideoSource;
class Friend;

class VideoSurface : public QQuickPaintedItem
{
    Q_OBJECT
public:
    VideoSurface(QQuickItem *parent = 0);
    void paint(QPainter *painter) override;
    Q_INVOKABLE void setSource(int friendId);

    void geometryChange(const QRectF& newGeometry, const QRectF& oldGeometry) override;
protected:
    bool isExpanding() const;

    QRectF getBoundingRect() const;
    float getRatio() const;
protected:
    void subscribe();
    void unsubscribe();
    void onNewFrameAvailable(const std::shared_ptr<vpx_image_t> newFrame);
    void onSourceStopped();

    // QQuickItem interface
protected:
    bool event(QEvent *event) override;

    void keyPressEvent(QKeyEvent *event) override;
    void keyReleaseEvent(QKeyEvent *event) override;
    void mousePressEvent(QMouseEvent *event) override;
    void mouseMoveEvent(QMouseEvent *event) override;
    void mouseReleaseEvent(QMouseEvent *event) override;
    void hoverMoveEvent(QHoverEvent *event) override;
    void wheelEvent(QWheelEvent *event) override;
    void touchEvent(QTouchEvent *event) override;

    void keyEventHandler(QKeyEvent *e);
    void wheelEventHandler(QWheelEvent *event);
    void mouseEventHandler(QMouseEvent *event);
    void hoverEventHandler(QHoverEvent *event);

private:
    void recalulateBounds();
    void lock();
    void unlock();
    void ProcessKeyEvent(int virtkey, uint64_t keyData);
    void SendKeyEvent(uint32_t key, bool down);
    void SendPointerEvent(int x, int y, int buttonMask);
    void SubProcessPointerEvent(int x, int y, uint64_t keyflags);
protected:
    bool		 m_bInit;

    int friendId;
    QRectF boundingRect;
    VideoSource* source;
    FRAME_PKG* lastFrame;
    QSizeF newSize;
    std::atomic_bool frameLock;
    uint8_t hasSubscribed;
    float ratio;
    bool expanding;
#ifdef _WIN32
    KeyMap m_keymap;
    std::map<uint8_t, KeyActionSpec> pressedKeys;
#endif

};

#endif // VIDEOSURFACE_H
